package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"news/cache"
	"news/models"
	"news/pkg"
	"strconv"
)

func NewsLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}
	login := "login" + username
	count, _ := cache.Rdb.Get(cache.Ctx, login).Int()

	if count >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, login)
		if count == 2 {
			cache.Rdb.Set(cache.Ctx, login, 3, 0)
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "密码错误3次，禁止登录",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return
}

func NewsList(c *gin.Context) {
	var news []models.News

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	list := "list" + strconv.Itoa(page)

	key, _ := cache.Rdb.Get(cache.Ctx, list).Result()

	if key == "" {
		models.DB.Offset(offset).Limit(size).Find(&news)

		jsonData, _ := json.Marshal(news)

		cache.Rdb.Set(cache.Ctx, key, jsonData, 0)
	} else {
		json.Unmarshal([]byte(key), &news)
	}

	var count int64
	models.DB.Model(&models.User{}).Count(&count)

	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  news,
		"count": count,
	})
	return
}

func NewsDetail(c *gin.Context) {
	id := c.Query("id")
	var news models.News

	key := "key" + id
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if cacheJson == "" {
		models.DB.Where("id = ?", id).First(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, key, jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheJson), &news)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": news,
	})
	return
}
